package com.itheima.health.config;

import com.itheima.health.common.RedisConst;
import com.itheima.health.service.SetMealService;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class ClearPictureTimer {
    //清理前等待时间 30分钟
    private static final Long WAIT_TIME = 30*60 * 1000L;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SetMealService setMealService;
    @Autowired
    private QiniuUtils qiniuUtils;
    @Scheduled(cron = "0 0 2 * * ?")//"秒分时日月周" *代表全部值，?代表不在乎周几
    public void run() {
        //遍历redis中的暂存图片信息，拿到一个垃圾图片的set集合
        Set<String> imgSet = redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).members();
        //清理垃圾图片
        for (String img : imgSet) {
            try {
                //优化1：清理图片时，有用户正在添加套餐
                //用户上传图片时间
                Long createTime = Long.valueOf(img.split("_", 2)[0]);
                // 当前时间-用户上传图片时间在等待时间之内，不删除
                if (System.currentTimeMillis() - createTime < WAIT_TIME) {
                    log.info("用户在等待时间之内上传图片，暂不删除:{}", img);
                    continue;
                }

                qiniuUtils.deleteFileFromQiniu(img);
                //清理redis上的所有图片
                redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).remove(img);
            }catch (Exception e){
                log.error("清理垃圾图片失败:" + img, e);
                continue;
            }
        }
        log.info("清理成功");

        }
}
